//
//  JourneyViewController.m
//  ITrip
//
//  Created by 1564335 on 15-5-31.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "JourneyViewController.h"
#import <UIImageView+AFNetworking.h>
#import <AFNetworking.h>
#import "URLPath.h"
#import "JourneyTableViewCell.h"
#import "JourneyParserModel1.h"
#import "UMSocial.h"
#import "Database.h"

@interface JourneyViewController ()<UITableViewDataSource, UITableViewDelegate, UMSocialUIDelegate>
{
    UITableView *GeneralTableView;
    UIImageView *iView;
    
}
@property(nonatomic, retain) UITableView *JourneyTableView;

@property(nonatomic, retain) JourneyParserModel1 *JourneyParser1;

@property(nonatomic, retain) UIButton *generalBtn;

@property(nonatomic, retain) UITapGestureRecognizer *tapGesture;

@property(nonatomic, retain) UIButton *shareBtn;

@property(nonatomic, retain) UIButton *collectBtn;

@end

@implementation JourneyViewController

- (void)dealloc
{
    [_JourneyParser1 release];
    [_JourneyTableView release];
    
    
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.tabBarController.tabBar.hidden  = YES;
    self.tabBarController.tabBar.translucent = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    UIImage *icon = [UIImage imageNamed:@"iconfont_return"];
    icon = [icon imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStyleDone target:self action:@selector(getBack)];
    
    UIImage *share = [UIImage imageNamed:@"iconfont-gengduo"];
    share = [share imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:share style:UIBarButtonItemStyleDone target:self action:@selector(shareAndCollect)];
    self.shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.collectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    
    self.shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.collectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    UIImage *shareBtn = [UIImage imageNamed:@"iconfont-share"];
    shareBtn = [shareBtn imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [self.shareBtn setImage:shareBtn forState:UIControlStateNormal];
    
    UIImage *collectBtn = [UIImage imageNamed:@"iconfont-shoucang"];
    collectBtn = [collectBtn imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [self.collectBtn setImage:collectBtn forState:UIControlStateNormal];
    
    self.shareBtn.frame = CGRectMake(self.view.frame.size.width - 50, -30, 30, 30);
    self.collectBtn.frame = CGRectMake(self.view.frame.size.width - 50, -30, 30, 30);
    self.shareBtn.layer.cornerRadius = 15;
    self.shareBtn.layer.masksToBounds = YES;
    self.collectBtn.layer.cornerRadius = 15;
    self.collectBtn.layer.masksToBounds = YES;
    
    self.shareBtn.backgroundColor = [UIColor grayColor];
    self.collectBtn.backgroundColor = [UIColor grayColor];
    
    self.shareBtn.alpha = 0.4;
    self.collectBtn.alpha = 0.4;
    
    [self.shareBtn addTarget:self action:@selector(share) forControlEvents:UIControlEventTouchUpInside];
    [self.collectBtn addTarget:self action:@selector(collect) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.view addSubview:self.shareBtn];
    [self.view addSubview:self.collectBtn];
    
    

    
    
    NSString *path = [[URLPath JourneyUrl] stringByAppendingFormat:@"%ld.json", self.number];
//    NSString *params = [NSString stringWithFormat:@"%ld.json", self.number];

    path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
    [manager GET:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingMutableContainers error:nil];
//        NSLog(@"%@", operation.responseData);
//        NSLog(@"%@", dic);
        self.JourneyParser1 = [[JourneyParserModel1 alloc] init:dic];
//        NSLog(@"%ld", self.JourneyParser1.arrayData.count);
        [self initTableView];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@", error);
    }];
    
    
}

- (void)shareAndCollect
{
    static NSInteger time = 0;
    if (time == 0) {
        [UIView animateWithDuration:0.5 animations:^{
            self.shareBtn.frame = CGRectMake(self.view.frame.size.width - 50, 0, 50, 50);
            self.collectBtn.frame = CGRectMake(self.view.frame.size.width - 50, 50, 50, 50);
            self.shareBtn.layer.cornerRadius = 25;
            self.shareBtn.layer.masksToBounds = YES;
            self.collectBtn.layer.cornerRadius = 25;
            self.collectBtn.layer.masksToBounds = YES;
        }];
        time = 1;
    } else {
        [UIView animateWithDuration:0.5 animations:^{
            self.shareBtn.frame = CGRectMake(self.view.frame.size.width - 50, -40, 40, 40);
            self.collectBtn.frame = CGRectMake(self.view.frame.size.width - 50, -40, 40, 40);
        }];
         time = 0;
    }
    
    [self.view bringSubviewToFront:self.shareBtn];
    [self.view bringSubviewToFront:self.collectBtn];
}


- (void)share
{
    [UIView animateWithDuration:0.5 animations:^{
        self.shareBtn.frame = CGRectMake(self.view.frame.size.width - 50, -40, 50, 50);
        self.collectBtn.frame = CGRectMake(self.view.frame.size.width - 50, -40, 50, 50);
    }];
    
    
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.JourneyParser1.image_url] options:NSDataReadingMappedAlways error:nil];
    UIImage *image = [UIImage imageWithData:data];
    NSString *str = self.JourneyParser1.name;
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"5569046f67e58e40e6002b92"
                                      shareText:str
                                     shareImage:image
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,nil]
                                       delegate:self];
}
- (void)collect
{
    [UIView animateWithDuration:0.5 animations:^{
        self.shareBtn.frame = CGRectMake(self.view.frame.size.width - 50, -40, 40, 40);
        self.collectBtn.frame = CGRectMake(self.view.frame.size.width - 50, -40, 40, 40);
    }];
    NSArray *array = [Database selectData];
    int i = 0;
    
    for (DbModel *model in array) {
        if (model.titleId == self.number) {
            i = 1;
            break;
        }
    }
    if (i == 1) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"您已经收藏过了!" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil , nil];
        [alert show];
    } else {
        DbModel *model = [DbModel getDbModel];
        model.title = self.JourneyParser1.name;
        model.titleId = self.number;
        model.choose = 2;
        model.imageURL = self.JourneyParser1.image_url;
        [Database insertValue:model];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"收藏成功!" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil , nil];
        [alert show];
    }
    
    
}


- (void)getBack
{
    self.generalBtn.hidden = YES;
    GeneralTableView.hidden = YES;
    if (self.isStrategy == 1) {
        self.tabBarController.tabBar.translucent = NO;
        self.tabBarController.tabBar.hidden = NO;
    }
    self.generalBtn.hidden = YES;
    [self.navigationController popViewControllerAnimated:YES];
}



- (void)getGeneral
{
    GeneralTableView.hidden = NO;
    [UIView animateWithDuration:0.5 animations:^{
        GeneralTableView.frame = CGRectMake(0, 0, 200, self.view.frame.size.height);
        self.generalBtn.frame = CGRectMake(20, self.view.frame.size.height, 40, 40);
    }];
    
}

#pragma -mark 隐藏目录
- (void)beginTouch
{
    [UIView animateWithDuration:0.5 animations:^{
        self.generalBtn.frame = CGRectMake(20, self.view.frame.size.height - 50, 40, 40);
        GeneralTableView.frame = CGRectMake(-200, 0, 200, self.view.frame.size.height);
        
    }];
    [UIView animateWithDuration:0.5 animations:^{
        self.shareBtn.frame = CGRectMake(self.view.frame.size.width - 50, -40, 40, 40);
        self.collectBtn.frame = CGRectMake(self.view.frame.size.width - 50, -40, 40, 40);
    }];
}

- (void)initTableView
{
    self.JourneyTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    self.JourneyTableView.delegate = self;
    self.JourneyTableView.dataSource = self;
    [self.view addSubview:self.JourneyTableView];
    self.JourneyTableView.tag = 1;
    [self.JourneyTableView release];
    
    
    
    // 添加点击
    self.tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(beginTouch)];
    [self.JourneyTableView addGestureRecognizer:self.tapGesture];
    
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 220)];
    
    iView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, headerView.frame.size.width, headerView.frame.size.height)];
    [iView setImageWithURL:[NSURL URLWithString:self.JourneyParser1.image_url] placeholderImage:[UIImage imageNamed:@"defaultPic_Down"]];
    
    self.JourneyTableView.tableHeaderView = headerView;
    [headerView addSubview:iView];
    NSInteger num = 0;
    for (JourneyParserModel2 *journeyParser2 in self.JourneyParser1.arrayData) {
        num += journeyParser2.arrayData.count;
    }
    
    UILabel *userName = [[UILabel alloc] initWithFrame:CGRectMake(20, 150, 280, 30)];
    userName.text = self.JourneyParser1.name;
    userName.textColor = [UIColor whiteColor];
    userName.font = [UIFont boldSystemFontOfSize:17];
    [headerView addSubview:userName];
    
    UILabel *date = [[UILabel alloc] initWithFrame:CGRectMake(20, 180, 280, 30)];
    date.text = [[NSString stringWithFormat:@"%ld", self.JourneyParser1.arrayData.count] stringByAppendingFormat:@"天 / %ld旅行地", num];
    date.textColor = [UIColor whiteColor];
    date.font = [UIFont boldSystemFontOfSize:15];
    [headerView addSubview:date];
    
    [date release];
    [userName release];
    [iView release];
    [headerView release];
    
    
    // 呼出概况栏
    self.generalBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.generalBtn.backgroundColor = [UIColor grayColor];
    [self.generalBtn setImage:[UIImage imageNamed:@"icon_list"] forState:UIControlStateNormal];
    self.generalBtn.frame = CGRectMake(20, self.view.frame.size.height - 50, 40, 40);
    [self.view addSubview:self.generalBtn];
    [self.view bringSubviewToFront:self.generalBtn];
    [self.generalBtn addTarget:self action:@selector(getGeneral) forControlEvents:UIControlEventTouchUpInside];
    self.generalBtn.layer.cornerRadius = 20;
    self.generalBtn.layer.masksToBounds = YES;
    self.generalBtn.layer.borderColor = [UIColor whiteColor].CGColor;
    self.generalBtn.layer.borderWidth = 2;
    
    // 添加第二个tableview
    GeneralTableView = [[UITableView alloc] initWithFrame:CGRectMake(-200, 0, 200, self.view.frame.size.height) style:UITableViewStylePlain];
    [self.view addSubview:GeneralTableView];
    [GeneralTableView release];
    GeneralTableView.alpha = 0.8;
    GeneralTableView.backgroundColor = [UIColor blackColor];
    GeneralTableView.delegate = self;
    GeneralTableView.dataSource = self;
    GeneralTableView.tag = 2;
    GeneralTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    GeneralTableView.hidden = YES;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    
    if (tableView.tag == 1) {
        JourneyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[JourneyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            cell.frame = CGRectMake(cell.frame.origin.x, cell.frame.origin.y, self.view.frame.size.width, cell.frame.size.height);
        }
        
        cell.tips.text = nil;
        cell.image_url.image = nil;
        cell.entry_name.text = nil;
        JourneyParserModel2 *journeyParser2 = [self.JourneyParser1.arrayData objectAtIndex:indexPath.section];
        JourneyParserModel3 *journeyParser3;
        if (indexPath.row == 0) {
            cell.titleView.frame = CGRectMake(20, 20, 30, 30);
            cell.titleView.backgroundColor = [UIColor clearColor];
            cell.titleView.layer.borderColor = [UIColor grayColor].CGColor;
//            cell.titleView.layer.borderWidth = 1.5;
//            cell.titleView.layer.cornerRadius = 20;
            cell.titleView.image = [UIImage imageNamed:@"iconfont-dingwei"];
            cell.titleView.layer.masksToBounds = YES;
            cell.entry_name.frame = CGRectMake(70, 30, 200, 25);
            cell.entry_name.text = @"今日备忘";
            cell.tips.frame = CGRectMake(20, 70, self.view.frame.size.width - 40, 30);
            cell.tips.text = journeyParser2.memo;
            cell.tips.numberOfLines = 1000;
            cell.tips.font = [UIFont systemFontOfSize:15];
            [cell.tips sizeToFit];
        } else {
            journeyParser3 = [journeyParser2.arrayData objectAtIndex:indexPath.row - 1];
            [cell setJourneyParser:journeyParser3];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    } else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];
        }
        cell.backgroundColor = [UIColor blackColor];
        JourneyParserModel2 *journeyParser2 = [self.JourneyParser1.arrayData objectAtIndex:indexPath.section];
        JourneyParserModel3 *journeyParser3 = nil;
        if (indexPath.row != 0) {
            journeyParser3 = [journeyParser2.arrayData objectAtIndex:indexPath.row - 1];
        }
        
        if (indexPath.row == 0) {
            
            cell.textLabel.textColor = [UIColor whiteColor];
            cell.textLabel.text = [NSString stringWithFormat:@"o DAY%ld", indexPath.section + 1];
            
        } else {
            cell.textLabel.text = [NSString stringWithFormat:@"o  %@", journeyParser3.entry_name];
            cell.textLabel.textColor = [UIColor whiteColor];
        }
        if (self.JourneyParser1.arrayData.count + 1 > indexPath.section) {
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(20, 35, 1, 15)];
            view.backgroundColor = [UIColor whiteColor];
            [cell addSubview:view];
            [view release];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;

    }
}

#pragma -mark tableView Selected
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 2) {
        if (indexPath.row == 0) {
            NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:indexPath.section];
            [self.JourneyTableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionTop animated:YES];
            [UIView animateWithDuration:0.5 animations:^{
                self.generalBtn.frame = CGRectMake(20, self.view.frame.size.height - 50, 40, 40);
                GeneralTableView.frame = CGRectMake(-200, 0, 200, self.view.frame.size.height);
                self.tapGesture.enabled = NO;
            }];
            
        } else {
            [self.JourneyTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
            [UIView animateWithDuration:0.5 animations:^{
                self.generalBtn.frame = CGRectMake(20, self.view.frame.size.height - 50, 40, 40);
                GeneralTableView.frame = CGRectMake(-200, 0, 200, self.view.frame.size.height);
                self.tapGesture.enabled = NO;
            }];
        }
        
        
    }

}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView.tag == 1) {
        return 50;
    }
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 1) {
        if (indexPath.row == 0) {
            JourneyParserModel2 *journeyParser2 = [self.JourneyParser1.arrayData objectAtIndex:indexPath.section];
            NSDictionary *dic = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:15] forKey:NSFontAttributeName];
            CGRect frame;
            
            if (journeyParser2.memo != nil) {
                frame = [journeyParser2.memo boundingRectWithSize:CGSizeMake(self.view.frame.size.width - 40, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
                return frame.size.height + 100;
            }

        }  else if (indexPath.row > 0) {
            //        NSLog(@"%ld, %ld, %@", indexPath.section, indexPath.row, model.entry_type);
            JourneyParserModel2 *journeyParser2 = [self.JourneyParser1.arrayData objectAtIndex:indexPath.section];
            JourneyParserModel3 *journeyParser3 = [journeyParser2.arrayData objectAtIndex:indexPath.row - 1];
            
            // 动态计算label高度
            NSDictionary *dic = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:15] forKey:NSFontAttributeName];
            CGRect frame;
            
            if (journeyParser3.tips != nil) {
                frame = [journeyParser3.tips boundingRectWithSize:CGSizeMake(self.view.frame.size.width - 40, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
            }
            
            if (journeyParser3.entry_type == nil) {// 无title
                if (journeyParser3.image_url.length == 0 && journeyParser3.tips.length == 0) {
                    // 都没有
                    return 0;
                } else if (journeyParser3.image_url == nil && journeyParser3.tips == nil) {
                    // 有图无文字
                    //            NSLog(@"%f", ((self.view.frame.size.width - 40) * (model.image_height / (CGFloat)model.image_width)));
                    return 240;
                    
                } else if (journeyParser3.image_url != nil && journeyParser3.tips != nil) {
                    // 有图有文字
                    //            NSLog(@"%f", (frame.size.height + ((self.view.frame.size.width - 40) * (model.image_height / (CGFloat)model.image_width))));
                    return frame.size.height + 240;
                } else {
                    // 纯文字
                    //            NSLog(@"%f", frame.size.height + 60);
                    //                NSLog(@"1");
                    //                NSLog(@"%f", frame.size.height);
                    return frame.size.height + 40;
                }
                
            } else  {
                // 有title
                if (journeyParser3.image_url == nil  && journeyParser3.tips == nil)  {
                    // 无图无文字
                    return 80;
                } else if (journeyParser3.image_url != nil && journeyParser3.tips.length == 0) {
                    // 有图无文字
                    //            NSLog(@"%f", ((self.view.frame.size.width - 40) * (model.image_height / (CGFloat)model.image_width)));
                    return 300;
                    
                } else if (journeyParser3.image_url != nil && journeyParser3.tips != nil) {
                    // 有图有文字
                    return 100 + frame.size.height + 240;
                    
                } else {
                    return 100 + frame.size.height;
                }
            }
        }
    }
    return 50;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.JourneyParser1.arrayData.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
        JourneyParserModel2 *JourneyParser2 = [self.JourneyParser1.arrayData objectAtIndex:section];
        return JourneyParser2.arrayData.count + 1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView.tag == 1) {
        UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width - 60, 50)]autorelease];
        view.backgroundColor = [UIColor whiteColor];
        UILabel *dayLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 70, 50)];
        [view addSubview:dayLabel];
        [dayLabel release];
        UILabel *dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(90, 0, 120, 50)];
        [view addSubview:dateLabel];
        dayLabel.textColor = [UIColor blackColor];
        dateLabel.textColor = [UIColor blackColor];
        [dateLabel release];
        JourneyParserModel2 *journeyParser2 = [self.JourneyParser1.arrayData objectAtIndex:section];
        JourneyParserModel3 *journeyParser3 = [journeyParser2.arrayData firstObject];
        dayLabel.text = [NSString stringWithFormat:@"DAY%ld", (section + 1)];
        dayLabel.font = [UIFont boldSystemFontOfSize:20];
        dateLabel.text = [NSString stringWithString:journeyParser3.name_zh_cn];
        
        return view;
    } else {
        return nil;
    }

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
